package com.ckd.flyingtrip.activity;

import android.Manifest;
import android.content.ContentResolver;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.bumptech.glide.Glide;
import com.ckd.flyingtrip.R;
import com.ckd.flyingtrip.constants.Constants;
import com.ckd.flyingtrip.javabean.UserInfoBean;
import com.ckd.flyingtrip.utils.BcUtils;
import com.ckd.flyingtrip.utils.DataCheck;
import com.ckd.flyingtrip.utils.SHA1Util;
import com.ckd.flyingtrip.utils.Tools;
import com.ckd.flyingtrip.utils.VolleyErrorUtils;
import com.ckd.flyingtrip.widge.SingleVolleyRequestQueue;
import com.donkingliang.imageselector.utils.ImageSelector;
import com.donkingliang.imageselector.utils.ImageUtil;
import com.google.gson.Gson;
import com.squareup.picasso.Picasso;
import com.yzq.zxinglibrary.common.Constant;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;
import me.nereo.multi_image_selector.MultiImageSelector;
import okhttp3.Call;

/*
 * 个人信息
 * */
public class UserInfoActivity extends BaseActivity {
    @BindView(R.id.btn_touxiang)
    LinearLayout btnTouxiang;
    @BindView(R.id.btn_nicheng)
    LinearLayout btnNicheng;
    @BindView(R.id.btn_xingming)
    LinearLayout btnXingming;
    @BindView(R.id.btn_shenfenzheng)
    LinearLayout btnShenfenzheng;
    @BindView(R.id.btn_xingbie)
    LinearLayout btnXingbie;
    @BindView(R.id.btn_shouhuodizhi)
    LinearLayout btnShouhuodizhi;
    @BindView(R.id.btn_res)
    Button btnRes;
    @BindView(R.id.img_touxiang)
    CircleImageView imgTouxiang;
    @BindView(R.id.txt_name)
    TextView txtName;
    @BindView(R.id.txt_nicheng)
    TextView txtNicheng;
    @BindView(R.id.txt_xingming)
    TextView txtXingming;
    @BindView(R.id.txt_shenfenzheng)
    TextView txtShenfenzheng;
    @BindView(R.id.txt_xingbie)
    TextView txtXingbie;
    @BindView(R.id.txt_dizhi)
    TextView txtDizhi;
    @BindView(R.id.toolber_color_title)
    TextView title;

    private int num = 3;
    private List<String> path = new ArrayList<>();
    private List<String> pathUrl = new ArrayList<>();
    private int numDataImg = 0;
    private List<String> imgData = new ArrayList<>();

    private Bitmap bitmap = null;
    /**
     * 需要进行检测的权限数组
     */
    protected String[] needPermissions = {
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.CAMERA
    };
    private static final int PERMISSON_REQUESTCODE = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_userinfo);
        ButterKnife.bind(this);
        info();
    }

    private void info() {
         title.setText("个人信息");
        volleyUserInfo();
    }

    @OnClick({R.id.btn_touxiang, R.id.btn_nicheng, R.id.btn_xingming, R.id.btn_shenfenzheng, R.id.btn_xingbie,
            R.id.btn_shouhuodizhi, R.id.btn_res})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_touxiang:

                ImageSelector.builder()
                        .useCamera(true) // 设置是否使用拍照
                        .setSingle(false)  //设置是否单选
                        .setMaxSelectCount(1) // 图片的最大选择数量，小于等于0时，不限数量。
                        .canPreview(true) //是否可以预览图片，默认为true
                        .start(UserInfoActivity.this, 11); // 打开相册
                break;
            case R.id.btn_nicheng:
                startActivityForResult_Value(UserInfoEditActivity.class, "nicheng", 1);
                break;
            case R.id.btn_xingming:
//                startActivityForResult_Value(UserInfoEditActivity.class, "xingming", 2);
                break;
            case R.id.btn_shenfenzheng:
//                startActivityForResult_Value(UserInfoEditActivity.class, "shenfenzheng", 3);
                break;
            case R.id.btn_xingbie:
                break;
            case R.id.btn_shouhuodizhi:
//                startActivityForResult_Value(UserInfoEditActivity.class, "shouhuodizhi", 4);
                startAction(UserInfoAddressActivity.class);
                break;
            case R.id.btn_res:
                if (bitmap == null) {
                    finish();
                    return;
                }
                createLoadingDialog(this, "正在上传...", true);
                initRes();
                break;
        }
    }

    private void initRes() {
        Log.e("上传头像", "上传头像开始");
        File file = null;
        try {
            file = saveFile(compressBitmap(bitmap, 200), getTime());
        } catch (IOException e) {
            e.printStackTrace();
        }
        OkHttpUtils.post()
                .addParams("userId", BcUtils.getUid())
                .addParams("suffix", ".png")
                .addFile("uploadImage", System.currentTimeMillis() + ".png", file)
                .url(Constants.TOUXIANG)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e("sss", e + "");
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        dismisProgressDialog();
                        Log.i("上传头像", response);
                        //s为请求返回的字符串数据
                        try {
                            JSONObject json = new JSONObject(response);
                            String code = json.getString("code");
                            String msg = json.getString("msg");
                            if (code.equals("1")) {
                                String data = json.getString("data");
                                BcUtils.getUserInfo().setUserHeadUrl(new JSONObject(data).getString("link"));
                                toast("保存成功！");
                                finish();
                            } else {
                                toast(msg);
                                Log.i("站好", "账号");
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            dismisProgressDialog();
                        }
                    }
                });

//        String url = Constants.TOUXIANG;
//        StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
//            @Override
//            public void onResponse(String s) {
//                dismisProgressDialog();
//                //s为请求返回的字符串数据
//                Log.e("上传头像", s);
//                try {
//                    JSONObject json = new JSONObject(s);
//                    String code = json.getString("code");
//                    if (code.equals("1")) {
//                        toast("上传成功");
//                        finish();
//                    } else {
//                        Log.i("站好", "账号");
//                    }
//                } catch (Exception e) {
//                    e.printStackTrace();
//                    dismisProgressDialog();
//                }
//            }
//        }, new Response.ErrorListener() {
//            @Override
//            public void onErrorResponse(VolleyError volleyError) {
//                Log.e("sss", volleyError + "");
//                dismisProgressDialog();
//                toast("请求失败");
//            }
//        }) {
//            @Override
//            protected Map<String, String> getParams() throws AuthFailureError {
//                HashMap<String, String> map = new HashMap<String, String>();
//                JSONObject json_url = new JSONObject();
//                JSONObject json_url1 = new JSONObject();
//                JSONObject json_url2 = new JSONObject();
//                FileInputStream fileInputStream = null;
//                try {
//                    File file = saveFile(compressBitmap(bitmap, 200), getTime());
//                    fileInputStream = new FileInputStream(file);
//                    json_url.put("uploadImage", fileInputStream);
//                    json_url1.put("userId", BcUtils.getUid());
//                    json_url2.put("suffix", ".PNG");
//                } catch (JSONException | IOException e) {
//                    e.printStackTrace();
//                }
////                map.put("uploadImage", fileInputStream + "");
//                map.put("uploadImage", "");
//                map.put("userId", BcUtils.getUid());
//                map.put("suffix", ".PNG");
//                return map;
//            }
//        };
//        SingleVolleyRequestQueue.getInstance(this).addToRequestQueue(request);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 11 && data != null) {
            ArrayList<String> images = data.getStringArrayListExtra(ImageSelector.SELECT_RESULT);
            Log.i("上传头像", images.get(0));
            Glide.with(this).load(images.get(0)).into(imgTouxiang);
//            bitmap = BitmapFactory.decodeStream(getClass().getResourceAsStream(images.get(0)));
            bitmap = ImageUtil.decodeSampledBitmapFromFile(this, images.get(0), 700, 700);
//            imgTouxiang.setImageBitmap(bitmap);
        }
        if (resultCode == RESULT_OK) {
            if (data == null)
                return;
            txtNicheng.setText(data.getStringExtra("data"));
        }
    }

    ///*
//* 个人信息
//* */
    public void volleyUserInfo() {
        final Gson mGson = new Gson();
        String url = Constants.QINGQIUGERENXINXI;
        StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                dismisProgressDialog();
                Log.i("用户信息", s);
                //s为请求返回的字符串数据
                try {
                    JSONObject json = new JSONObject(s);
                    String code = json.getString("code");
                    String msg = json.getString("msg");
                    if (code.equals("1")) {
                        JSONObject dataInfo = json.getJSONObject("data");
                        String data = json.getString("data");
                        UserInfoBean userInfoBean = mGson.fromJson(data, UserInfoBean.class);
                        BcUtils.setUserInfo(userInfoBean);

                        if (Tools.isEmpeyNull(userInfoBean.getUserHeadUrl())) {
                            Glide.with(UserInfoActivity.this).load(userInfoBean.getUserHeadUrl()).into(imgTouxiang);
                        }
                        txtName.setText(userInfoBean.getUserPhone());
                        txtNicheng.setText(userInfoBean.getUserNickname());

                        txtXingming.setText(userInfoBean.getUserName());
                        txtShenfenzheng.setText(userInfoBean.getUserIdNum());
                        txtXingbie.setText(userInfoBean.getUserGender());
                    } else {
                        Log.i("站好", "账号");
                        toast(msg);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    dismisProgressDialog();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                dismisProgressDialog();
                VolleyErrorUtils.checkError(volleyError);
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {//创建请求参数

                HashMap<String, String> map = new HashMap<String, String>();
                JSONObject json_url = new JSONObject();
                try {
                    json_url.put("userId", BcUtils.getUid());
                    json_url.put("userPhone", BcUtils.getUserInfo().getUserPhone());
                    json_url.put("token", BcUtils.getToken());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                map.put("inputParameter", DataCheck.signCheck(json_url.toString()));
                return map;
            }
        };
        SingleVolleyRequestQueue.getInstance(this).addToRequestQueue(request);
    }

    public File saveFile(Bitmap bm, String fileName) throws IOException {
        String path = Environment.getExternalStorageDirectory() + "/Ask";
        File dirFile = new File(path);
        if (!dirFile.exists()) {
            dirFile.mkdir();
        }
        File myCaptureFile = new File(path + fileName);
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
        bm.compress(Bitmap.CompressFormat.PNG, 80, bos);
        bos.flush();
        bos.close();
        return myCaptureFile;
    }

    public String getTime() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        String timeString = formatter.format(curDate);

        String timeStamp = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 hh:mm");
        Date d;
        try {
            d = sdf.parse(timeString);
            long l = d.getTime();
            timeStamp = String.valueOf(l);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return timeStamp;
    }

    private Bitmap compressBitmap(Bitmap bitmap, long sizeLimit) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int quality = 100;
        bitmap.compress(Bitmap.CompressFormat.JPEG, quality, baos);
        while (baos.toByteArray().length / 1024 > sizeLimit) {
            baos.reset();
            bitmap.compress(Bitmap.CompressFormat.JPEG, quality, baos);
            quality -= 10;
        }
        Bitmap newBitmap = BitmapFactory.decodeStream(new ByteArrayInputStream(baos.toByteArray()), null, null);
        return newBitmap;
    }

    @OnClick(R.id.toolber_color_back)
    public void onViewClicked() {
        finish();
    }

}
